import getpath
import os
import xlrd
import re
import logging
import copy
import myglobal
import config_json
import sample
import openpyxl
def elementWave(s):
    logging.info([s,type(s)])
    find = re.search(r"\d+(\.\d+)?  [A-Z][a-z]*", s).group()
    (wave,element)=find.split("  ")
    mode=s.split("[")[1].split("]")[0].strip().replace(" ","")
    return(element,wave+"."+mode)
def getdata_raw(fname):
    from openpyxl import load_workbook
    xl_book = load_workbook(filename=fname)
    table = xl_book.worksheets[0]
    data = []
    for row in table.values:
        r = []
        for one in row:
            if one is not None:
                r.append(one)
            else:
                r.append("")
        data.append(r)
    return data    
def zl_data(data):
    # {"id":id1,"mass":wt,"volume":volume,"items":eles}
    at=0
    start=0
    for one in data[1]:
        if "稀释" in one:
            start=at+1
            break
        at+=1
    logging.info(["start",start])
    data_ele=data[0][start:]
    at=0
    items=[]
    colidx=[]
    neibiao=False
    while(at<len(data_ele)):
        logging.info(at+start)
        if "内标" in data_ele[at]:
            neibiao=True
        r=elementWave(data_ele[at])
        if neibiao:
            r=(r[0]+".内标",r[1])#,False,r[3])
        if neibiao:
            # items[r]=at+start
            items.append(r)
            colidx.append(at+start)
        else:
            # items[r]=at+start
            items.append(r)
            colidx.append(at+start)
            # items[(r[0]+"_CPS",r[1],False,r[3])]=at+start+1
            items.append((r[0]+".CPS",r[1]))#,False,r[3]))
            colidx.append(at+start+1)
        if neibiao:
            at+=1
        else:
            at+=2
    data=data[2:]
    r=[]
    for i in range(len(data)):
        sample={}
        # sample["items"]=copy.copy(items)
        row=data[i]
        id1=row[start-2]
        # type1=row[4]
        # conc=row[8]
        if id1=="":
            continue
        sample["sampleid"]=str(id1)
        sample["xishi"]=""
        mass=(1/myglobal.myfloat(row[start-1]))/10.0
        sample["mass"]="%.4f" % mass
        sample["conc"]=[]
        if mass>0.06:
            sample["volume"]="100"
        else:
            sample["volume"]="50"
        for i in range(len(items)):
            conc=row[colidx[i]]
            sample["conc"].append(conc)
        r.append(sample)
    return (items,r)
def getdata(fname):
    data0=getdata_raw(fname)
    data=zl_data(data0)
    return data
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","data","031974-4.xlsx")
    data=getdata(fname)
    # print(data)
    return data